var JJZ = {};

JJZ.SHOW_PASSWORD = '******';

JJZ.defaultSelectParam = 'current=1&pageSize=99999';

//JJZ.baseUrl = 'http://203.195.217.240:8080/device';

JJZ.baseUrl = 'http://127.0.0.1:8080/device';


JJZ.NavUrl = {
    indexNav: 'indexNav',
    deviceNav: 'deviceNav',
    faultNav: 'faultNav',
    taskNav: 'taskNav',
    componentNav: 'componentNav',
    commentNav: 'commentNav',
    userNav: 'userNav'
};

JJZ.initMultipleSelect = function (formSelects, xmSelect, url, field, callback) {

    JJZ.requestData(url, JJZ.defaultSelectParam, function (data) {
        var records = data.records;
        var arr = [];
        for (var index in records) {
            // 新建OPTION (op)
            var temp = {};
            temp.value = records[index]['id'];
            temp.name = records[index][field];
            arr.push(temp);
        }
        formSelects.data(xmSelect, 'local', {
            arr: arr
        });
        callback & callback(true);
    })

};

JJZ.initMultipleSelect2 = function (formSelects, xmSelect, url, param, field, callback) {

    JJZ.requestData(url, param, function (data) {
        var records = data.records;
        var arr = [];
        for (var index in records) {
            // 新建OPTION (op)
            var temp = {};
            temp.value = records[index]['id'];
            temp.name = records[index][field];
            arr.push(temp);
        }
        formSelects.data(xmSelect, 'local', {
            arr: arr
        });
        callback & callback(true);
    })

};

JJZ.initMultipleSelectReturnData = function (formSelects, xmSelect, url, param, field, callback) {

    JJZ.requestData(url, param, function (data) {
        var records = data.records;
        var arr = [];
        for (var index in records) {
            // 新建OPTION (op)
            var temp = {};
            temp.value = records[index]['id'];
            temp.name = records[index][field];
            arr.push(temp);
        }
        formSelects.data(xmSelect, 'local', {
            arr: arr
        });
        callback & callback(arr);
    })

};

JJZ.initSelect = function (selector, url, callback) {
    JJZ.requestData(url, JJZ.defaultSelectParam, function (data) {
        var records = data.records;
        for (var index in records) {
            // 新建OPTION (op)
            var op = document.createElement("option");
            op.value = records[index].id;
            op.innerText = records[index].name;
            $(op).data(records[index]);
            $(selector).append(op);
        }
        callback & callback(true);
    })
};

JJZ.initSelectWithParam = function (selector, url,param, callback) {
    JJZ.requestData(url, param, function (data) {
        var records = data.records;
        for (var index in records) {
            // 新建OPTION (op)
            var op = document.createElement("option");
            op.value = records[index].id;
            op.innerText = records[index].name;
            $(op).data(records[index]);
            $(selector).append(op);
        }
        callback & callback(true);
    })
};

JJZ.initSelectWithParamAndShowField = function (selector, url,param,field, callback) {
    JJZ.requestData(url, param, function (data) {
        var records = data.records;
        for (var index in records) {
            // 新建OPTION (op)
            var op = document.createElement("option");
            op.value = records[index].id;
            op.innerText = records[index][field];
            $(op).data(records[index]);
            $(selector).append(op);
        }
        callback & callback(true);
    })
};

JJZ.initSelectWithParamAndShow2Field = function (selector, url,param,field1,field2, callback) {
    JJZ.requestData(url, param, function (data) {
        var records = data.records;
        for (var index in records) {
            var op = document.createElement("option");
            op.value = records[index].id;
            op.innerText = records[index][field1]+"("+records[index][field2]+")";
            $(op).data(records[index]);
            $(selector).append(op);
        }
        callback & callback(true);
    })
};

JJZ.initSelectShowField = function (selector, url, field, callback) {
    JJZ.requestData(url, JJZ.defaultSelectParam, function (data) {
        var records = data.records;
        for (var index in records) {
            // 新建OPTION (op)
            var op = document.createElement("option");
            op.value = records[index]['id'];
            op.innerText = records[index][field];
            $(op).data(records[index]);
            $(selector).append(op);
        }
        callback & callback(true);
    })
};


JJZ.addData = function (table, content, callback) {
    var encodeStr = $.base64.encode(JSON.stringify(content), 'utf-8');
    var param = 'json=' + encodeURIComponent(encodeStr);
    JJZ.ajax('POST', '/' + table + '/add', param, function (data) {
        var json = JSON.parse(data);
        if (json.success === true) {
            callback & callback(json.content);
        } else {
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg, {icon: 2});
        }
    })
}

JJZ.editData = function (table, content, callback) {
    var encodeStr = $.base64.encode(JSON.stringify(content), 'utf-8');
    var param = 'json=' + encodeURIComponent(encodeStr);
    JJZ.ajax('POST', '/' + table + '/edit', param, function (data) {
        var json = JSON.parse(data);
        if (json.success === true) {
            callback & callback(json.content);
        } else {
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg, {icon: 2});
        }
    })
}


JJZ.requestData = function (url, param, callback) {
    JJZ.ajax('POST', url, param, function (data) {
        var json = JSON.parse(data);
        if (json.success === true) {
            callback & callback(json.content);
        } else {
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg, {icon: 2});
        }
    })
}


JJZ.requestTableData = function (table, param, callback) {
    //param 格式 a=1&b=2
    if(param === ''){
        param = JJZ.defaultSelectParam;
    }
    JJZ.ajax('POST', '/' + table + '/dataGrid', param, function (data) {
        var json = JSON.parse(data);
        if (json.success === true) {
            callback & callback(json.content);
        } else {
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg, {icon: 2});
        }
    })
}


JJZ.MyTable = function (tableInfo) {

    var defaultPageSize = 10;

    tableInfo.searchCol = tableInfo.searchCol?tableInfo.searchCol:'';
    tableInfo.searchValue = tableInfo.searchValue?tableInfo.searchValue:'';
    //渲染方法的使用,默认没有筛选条件的查询
    this.render = function () {

        //requestUrl 不使用默认的请求地址
       // initParam   初始化请求参数的后半段，即不包括分页参数

        //如果自身传递了参数则表示携带了筛选条件
        layui.use(['table', 'laypage'], function () {
            var table = layui.table;
            var laypage = layui.laypage;
            var pageDiv = tableInfo.pageDiv;
            var initLimit = tableInfo.limit;
            var pageRenderObject = {
                elem: pageDiv && pageDiv != '' ? pageDiv : 'pageDiv'
                , layout: ['count', 'prev', 'page', 'next', 'limit']
                , limit: initLimit && initLimit!=''?initLimit:defaultPageSize
                , jump: function (obj, first) {
                    //首次不执行
                    if (!first) {
                        if (tableInfo.requestUrl && tableInfo.requestUrl != '') {
                            //表示是使用自定义的请求参数，不通过tableName来访问dataGrid接口
                            var suffix = tableInfo.initParam && tableInfo.initParam != '' ? tableInfo.initParam : 'searchCol=' + tableInfo.searchCol + '&searchValue=' + tableInfo.searchValue;
                            var pageParam = 'current=' + obj.curr + '&pageSize=' + obj.limit + '&' + suffix;
                            JJZ.requestData(tableInfo.requestUrl, pageParam, function (data) {
                                tableInfo.data = data.records;
                                pageRenderObject.count = data.total;
                                laypage.render(pageRenderObject);
                                defaultPageSize = pageRenderObject.limit;
                                tableInfo.limit = defaultPageSize;
                                table.render(tableInfo);
                            });
                        } else {
                            var suffix = tableInfo.initParam && tableInfo.initParam != '' ? tableInfo.initParam : 'searchCol=' + tableInfo.searchCol + '&searchValue=' + tableInfo.searchValue;
                            var pageParam = 'current=' + obj.curr + '&pageSize=' + obj.limit + '&' + suffix;
                            JJZ.requestTableData(tableInfo.tableName, pageParam, function (data) {
                                tableInfo.data = data.records;
                                pageRenderObject.count = data.total;
                                laypage.render(pageRenderObject);
                                defaultPageSize = pageRenderObject.limit;
                                tableInfo.limit = defaultPageSize;
                                table.render(tableInfo);
                            });
                        }
                    }
                }
            };

            if (tableInfo.requestUrl && tableInfo.requestUrl != '') {
                //表示是使用自定义的请求参数，不通过tableName来访问dataGrid接口
                var suffix = tableInfo.initParam && tableInfo.initParam != '' ? tableInfo.initParam : 'searchCol=' + tableInfo.searchCol + '&searchValue=' + tableInfo.searchValue;
                var param = 'current=1&pageSize=' + pageRenderObject.limit + '&' + suffix;
                JJZ.requestData(tableInfo.requestUrl, param, function (data) {
                    tableInfo.data = data.records;
                    pageRenderObject.count = data.total;
                    var limit = tableInfo.limit;
                    tableInfo.limit = limit && limit!=''?limit:defaultPageSize;
                    laypage.render(pageRenderObject);
                    table.render(tableInfo);
                });
            } else {
                var suffix = tableInfo.initParam && tableInfo.initParam != '' ? tableInfo.initParam : 'searchCol=' + tableInfo.searchCol + '&searchValue=' + tableInfo.searchValue;
                var param = 'current=1&pageSize=' + pageRenderObject.limit + '&' + suffix;
                JJZ.requestTableData(tableInfo.tableName, param, function (data) {
                    tableInfo.data = data.records;
                    pageRenderObject.count = data.total;
                    var limit = tableInfo.limit;
                    tableInfo.limit = limit && limit!=''?limit:defaultPageSize;
                    laypage.render(pageRenderObject);
                    table.render(tableInfo);
                });
            }

        });
    };

    //跳转到添加页面
    this.add = function () {
        //先访问一遍判断是否有权限，然后根据具体情况进行处理
        JJZ.ajax('GET', '/'+tableInfo.tableName+'/add', '', function (data) {
            if(JJZ.isJsonString(data)){
                //get请求如果返回的内容是json则表示一定出现了错误
                var json = JSON.parse(data);
                layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg, {icon: 2});
            }else{
                window.location.href = JJZ.baseUrl + '/' + tableInfo.tableName + '/add';
            }
        })
    };

    //批量删除方法
    this.delete = function (data) {
        if (data.length === 0) {
            layer.msg('请至少选择一行需要删除的数据');
        } else {
            var temp = [];
            for (var index in data) {
                temp.push(data[index].id);
            }
            var encodeStr = $.base64.encode(JSON.stringify(temp), 'utf-8');
            var param = 'json=' + encodeURIComponent(encodeStr);

            JJZ.ajax('POST', '/' + tableInfo.tableName + '/delete', param, function (data) {
                var json = JSON.parse(data);
                if (json.success === false) {
                    layer.msg(json.errorMsg);
                }
            })
        }
    };

    this.render();

};

JJZ.currUser = function(){
    var user = window.sessionStorage.getItem("loginUser");
    var jsonUser = JSON.parse(user);
    return jsonUser;
};

JJZ.login = function (userName, password, callback) {

    var param = 'loginName=' + userName + '&password=' + password;
    JJZ.ajax('POST', '/login', param, function (data) {
        var json = JSON.parse(data);
        if (json.success === true) {
            window.sessionStorage.setItem("loginUser", JSON.stringify(json.content));
            window.location.href = JJZ.baseUrl + '/index';
        } else {
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg, {icon: 2});
        }
    })


}

JJZ.logout = function () {
    window.sessionStorage.clear();
    window.location.href = JJZ.baseUrl + '/logout';
}


JJZ.editPage = function(tableName,id){
    JJZ.ajax('GET', '/'+tableName+'/edit', 'id='+id, function (data) {
        if(JJZ.isJsonString(data)){
            //get请求如果返回的内容是json则表示一定出现了错误
            var json = JSON.parse(data);
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg);
        }else{
            window.location.href = JJZ.baseUrl + '/' + tableName + '/edit?id='+id;
        }
    })
};

JJZ.getRequestToPage = function(url){
    JJZ.ajax('GET', url, '', function (data) {
        if(JJZ.isJsonString(data)){
            //get请求如果返回的内容是json则表示一定出现了错误
            var json = JSON.parse(data);
            layer.msg('错误码:' + json.errorCode + ';错误信息:' + json.errorMsg);
        }else{
            window.location.href = JJZ.baseUrl + url;
        }
    })
};


JJZ.checkGetRequestPermission = function(url,callback){
    JJZ.ajax('GET', url,'',function (data) {
        if(JJZ.isJsonString(data)){
                callback(false);
        }else{
            callback(true);
        }
    })
};

JJZ.isJsonString =function(str) {
    try {
        if (typeof JSON.parse(str) == "object") {
            return true;
        }
    } catch(e) {
    }
    return false;
}


JJZ.ajax = function (method, url, data, callback) {
    url = JJZ.baseUrl + url;
    var xhr;
    //1.创建对象，兼容问题
    if (window.XMLHttpRequest) {
        //在高版本的浏览器 IE7+
        xhr = new XMLHttpRequest();
        //XMLHttpRequest用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。
    } else {
        //IE5 IE6
        xhr = new ActiveXObject();
    }
    //2.发送请求
    //第一个参数：数据传输方式 get post
    //第二个参数：处理文件 xx.php xx.txt ，要数据：直接写路径就好；提交数据：在地址那里写数据（get方式）
    //第三个参数：同步或者异步方式，默认是异步true
    //open
    //get模式路径上同时加入需要传输的内容
    if (method == 'GET' && data) {
        url = url + '?' + data;
    }
    xhr.open(method, url, true);
    //send
    //send()如果是get方式，写null或者为空；
    //如果是post，参数那就直接写要传输的内容
    if (method == 'GET') {
        xhr.send(null);
    } else {
        //创建头文件信息
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(data);
    }
    //4.接受后台传过来的数据，解析 dom操作
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {//响应过程状态信息，4代表发送完成，顺利返回信息
            if (xhr.status == 200) {//status:状态码，如果返回的信息是200
                callback && callback(xhr.responseText);
            } else {
                if(xhr.status == 401){
                    layer.msg('无权访问');
                }else{
                    layer.msg('系统内部错误', {icon: 2});
                }
            }
        }
    }
}


JJZ.named = function (nm) {
    var str = "[name='-']:first";
    var replace = str.replace(/-/g, nm);
    var dom = $(replace);
    return dom;
};


JJZ.FormatDate = function (datetime, fmt) {
    if(typeof(datetime) === 'string'){
        datetime = datetime.replace(new RegExp(/-/gm),"/");
    }
    if (parseInt(datetime) == datetime) {
        if (datetime.length == 10) {
            datetime = parseInt(datetime) * 1000;
        } else if (datetime.length == 13) {
            datetime = parseInt(datetime);
        }
    }
    datetime = new Date(datetime);

    var o = {
        "M+": datetime.getMonth() + 1,                 //月份
        "d+": datetime.getDate(),                    //日
        "h+": datetime.getHours(),                   //小时
        "m+": datetime.getMinutes(),                 //分
        "s+": datetime.getSeconds(),                 //秒
        "q+": Math.floor((datetime.getMonth() + 3) / 3), //季度
        "S": datetime.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//定义两个变量time1,time2分别保存开始和结束时间
JJZ.TimeDifference = function (time1, time2) {
//判断开始时间是否大于结束日期
    if (time1 > time2) {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    //截取字符串，得到日期部分"2009-12-02",用split把字符串分隔成数组
    var begin1 = time1.substr(0, 10).split("-");
    var end1 = time2.substr(0, 10).split("-");
//将拆分的数组重新组合，并实例成化新的日期对象
    var date1 = new Date(begin1[1] + -+begin1[2] + -+begin1[0]);
    var date2 = new Date(end1[1] + -+end1[2] + -+end1[0]);
    //得到两个日期之间的差值m，以分钟为单位
    //Math.abs(date2-date1)计算出以毫秒为单位的差值
    //Math.abs(date2-date1)/1000得到以秒为单位的差值
    //Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
    var m = parseInt(Math.abs(date2 - date1) / 1000 / 60);
    //小时数和分钟数相加得到总的分钟数
    //time1.substr(11,2)截取字符串得到时间的小时数
    //parseInt(time1.substr(11,2))*60把小时数转化成为分钟
    var min1 = parseInt(time1.substr(11, 2)) * 60 + parseInt(time1.substr(14, 2));
    var min2 = parseInt(time2.substr(11, 2)) * 60 + parseInt(time2.substr(14, 2));
    //两个分钟数相减得到时间部分的差值，以分钟为单位
    var n = min2 - min1;
    //将日期和时间两个部分计算出来的差值相加，即得到两个时间相减后的分钟数
    var minutes = m + n;
    return minutes;
}

JJZ.getNowFormatDate = function () {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
};

JJZ.getNowFormatYearMonth = function () {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    } else {
        month = "" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + month;
    return currentdate;
};


JJZ.getNowYearMonthDay = function () {
    var date = new Date();
    var seperator1 = "-";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
    return currentdate;
};
/**
 * 获取上一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
 */
JJZ.getPreMonth = function (date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
};

/**
 * 获取下一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
 */
JJZ.getNextMonth = function (date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中的月的天数
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }

    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}

/**
 * 获得当前月份的前一个月
 * @param date
 * @returns {*}
 */
JJZ.getNowMonthPreMonth = function () {
    var date = JJZ.getNowYearMonthDay();
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + month2;
    return t2;
};

/**
 * 获得当前月份的下一个月
 * @param date
 * @returns {*}
 */
JJZ.getNowNextMonth = function () {
    var date = JJZ.getNowYearMonthDay();
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中的月的天数
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + month2;
    return t2;
}

JJZ.getPastHalfYear = function () {
    // 先获取当前时间
    var curDate = (new Date()).getTime();
    // 将半年的时间单位换算成毫秒
    var halfYear = 365 / 2 * 24 * 3600 * 1000;
    var pastResult = curDate - halfYear;  // 半年前的时间（毫秒单位）
    // 日期函数，定义起点为半年前
    var pastDate = new Date(pastResult),
        pastYear = pastDate.getFullYear(),
        pastMonth = pastDate.getMonth() + 1;
    if (pastMonth >= 1 && pastMonth <= 9) {
        pastMonth = "0" + pastMonth;
    } else {
        pastMonth = "" + pastMonth;
    }
    return pastYear + "" + pastMonth;
};


JJZ.CommonFunction = {
    // 判断字符串是否为空
    isEmpty: function (value) {
        if (value == null || this.trim(value) == "") {
            return true;
        }
        return false;
    },
    // 判断一个字符串是否为非空串
    isNotEmpty: function (value) {
        return !$.common.isEmpty(value);
    },
    // 空对象转字符串
    nullToStr: function(value) {
        if ($.common.isEmpty(value)) {
            return "-";
        }
        return value;
    },
    // 是否显示数据 为空默认为显示
    visible: function (value) {
        if ($.common.isEmpty(value) || value == true) {
            return true;
        }
        return false;
    },
    // 空格截取
    trim: function (value) {
        if (value == null) {
            return "";
        }
        return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
    },
    // 比较两个字符串（大小写敏感）
    equals: function (str, that) {
        return str == that;
    },
    // 比较两个字符串（大小写不敏感）
    equalsIgnoreCase: function (str, that) {
        return String(str).toUpperCase() === String(that).toUpperCase();
    },
    // 将字符串按指定字符分割
    split: function (str, sep, maxLen) {
        if ($.common.isEmpty(str)) {
            return null;
        }
        var value = String(str).split(sep);
        return maxLen ? value.slice(0, maxLen - 1) : value;
    },
    // 字符串格式化(%s )
    sprintf: function (str) {
        var args = arguments, flag = true, i = 1;
        str = str.replace(/%s/g, function () {
            var arg = args[i++];
            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    },
    // 指定随机数返回
    random: function (min, max) {
        return Math.floor((Math.random() * max) + min);
    },
    // 判断字符串是否是以start开头
    startWith: function(value, start) {
        var reg = new RegExp("^" + start);
        return reg.test(value)
    },
    // 判断字符串是否是以end结尾
    endWith: function(value, end) {
        var reg = new RegExp(end + "$");
        return reg.test(value)
    },
    // 数组去重
    uniqueFn: function(array) {
        var result = [];
        var hashObj = {};
        for (var i = 0; i < array.length; i++) {
            if (!hashObj[array[i]]) {
                hashObj[array[i]] = true;
                result.push(array[i]);
            }
        }
        return result;
    }
};



